package org.apache.maven.plugin.echo;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.IllegalFormatException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

/**
 * Goal which echoes a line to the console. If the line contains any formatting
 * and an additional elements array is present then this applied to it.
 * 
 * @goal echo
 * 
 * @phase install
 */
public class EchoMojo extends AbstractMojo {

	private static final String INFO = "info";

	private static final String DEBUG = "debug";

	private static final String ILLEGAL_FORMAT = "Illegal formatting found, please check your %s element";

	/**
	 * What to echo to the console at info level
	 * 
	 * @parameter expression="${echo.info}"
	 */
	private String info;

	/**
	 * What to echo to the console at debug level
	 * 
	 * @parameter expression="${echo.debug}"
	 */
	private String debug;

	/**
	 * The elements in this list are applied to the log line as per the {@code}
	 * String.format() specification
	 * 
	 * @parameter expression="${echo.elements}"
	 */
	private String[] elements;

	public void execute() throws MojoExecutionException {
		if (debug != null) {
			if (getLog().isDebugEnabled()) {
				try {
					getLog().debug(String.format(debug, elements));
				} catch (IllegalFormatException ife) {
					throw new MojoExecutionException(String.format(
							ILLEGAL_FORMAT, DEBUG));
				}
			}
		}

		if (info != null) {
			if (getLog().isInfoEnabled()) {
				try {
					getLog().info(String.format(info, elements));
				} catch (IllegalFormatException ife) {
					throw new MojoExecutionException(String.format(
							ILLEGAL_FORMAT, INFO));
				}
			}
		}
	}

	public void setInfo(final String info) {
		this.info = info;
	}

	public String getInfo() {
		return info;
	}

	public void setDebug(final String debug) {
		this.debug = debug;
	}

	public String getDebug() {
		return debug;
	}

	public void setFormat(String[] format) {
		this.elements = format;
	}

	public String[] getFormat() {
		return elements;
	}
}
